<?php

namespace app\company\controller\report;

use app\common\controller\CompanyController;
use app\common\Jobs\ReportGoodsOutJob;
use app\common\model\Dealer;
use app\common\model\DealerGoods;
use app\common\model\DealerGoodsCate;
use app\common\model\DealerGoodsSpec;
use app\common\model\DeliveryLog;
use app\common\model\GoodsCate;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\company\controller\DealerGoods as ControllerDealerGoods;
use app\company\model\CompanyOrder;
use app\company\model\CompanyOrderDetail;
use app\company\model\Delivery;
use app\company\model\DealerOrder;
use app\company\model\DealerOrderDetail;
use app\company\model\ReportGoodsOut;
use app\company\model\ReportPurchaseOut;
use Company;
use think\App;
use think\Paginator;
use think\response\Json;
use jianyan\excel\Excel;
use app\company\model\CompanyPickOrder;
use think\facade\Queue;

/**
 * @ControllerAnnotation(title="仓库报表")
 */
class Warehouse extends CompanyController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new ReportGoodsOut();
    }

    /**
     * @NodeAnnotation(title="仓库 出库报表 ")
     */
    public function out_list()
    {
        $param = $this->request->get();
        $report_goods_out_model = new ReportGoodsOut();
        $where = [];

        if (isset($param['type'])) {
            $where[] = ['type', '=', $param['type']];
        } else {
            $where[] = ['type', '=', 1];
        }
        $filter = [];
        if (isset($param['filter'])) {
            $filter = json_decode(stripslashes($param['filter']), true);
        }

        if (!empty($filter['create_time'])) {
            $create_time = $filter['create_time'];
            $beginTime = strtotime($create_time[0]);
            $endTime = strtotime('+1 day -1 second', strtotime($create_time[1]));
            $where[] = ['create_time', '>=', $beginTime];
            $where[] = ['create_time', '<=', $endTime];
        }

        if (!empty($filter['goods_name'])) {
            $goodsIds = DealerGoods::where('name', 'like', '%' . $filter['goods_name'] . '%')->column('id');
            $where[] = ['dealer_goods_id', 'in', $goodsIds];
        }
        if (!empty($filter['dealer_name'])) {
            $dealerIds = DealerGoodsSpec::where('dealer_name', 'like', '%' . $filter['dealer_name'] . '%')->column('dealer_id');
            $where[] = ['dealer_id', 'in', $dealerIds];
        }
        if (!empty($filter['dealer_cate_id'])) {
            $where[] = ['dealer_cate_id', '=', $filter['dealer_cate_id']];
        }

        if (!empty($filter['dealer_id'])) {
            $where[] = ['dealer_id', '=', $filter['dealer_id']];
        }

        $sql = $this->model->where($this->defaultWhere)->where($where)
            ->order(['id' => 'desc'])->group('dealer_goods_id,dealer_id')
            ->field('*,sum(big_unit_out_value+middle_unit_out_value+small_unit_out_value) as total_out_value
            ,sum(small_unit_out_num) as small_unit_out_num
        ,sum(middle_unit_out_num) as middle_unit_out_num
        ,sum(big_unit_out_num) as big_unit_out_num');

        if (isset($param['export']) && $param['export'] == true) {
            $list = $sql->select()->toArray();
            $list = $this->eachList($list);
        } else {
            $list = $sql->paginate($param['limit'])->toArray();
            $list['data'] = $this->eachList($list['data']);


            //合计
            $all_data = $sql->select()->toArray();
            $all_data = $this->eachList($all_data);
            $list['total_out_num'] = array_sum(array_column($all_data, 'total_out_num_small'));
            $list['total_out_value'] = array_sum(array_column($all_data, 'total_out_value'));
        }

        //服务费用
        if (isset($param['export']) && $param['export'] == true) {
            $header = [
                ['商品名称', 'goods_name'],
                ['商品编码', 'code69'],
                ['商品分类', 'cate_name'],
                ['出库数量', 'total_out_num'],
                ['出库货值', 'total_out_value'],
                ['经销商', 'dealer_name'],

            ];


            $fileName = '仓库出库报表';
            return Excel::exportData($list, $header, $fileName, 'xlsx');
        } else {
            return $this->success($list);
        }
    }

    private function eachList($list)
    {
        $dealer_model = new Dealer();
        $cate_model = new GoodsCate();
        $goods_model = new DealerGoods();
        foreach ($list as &$item) {

            $goodsInfo = $goods_model->where('id', $item['dealer_goods_id'])->field('name,code69')->withTrashed()->find();
            $item['goods_name'] = $goodsInfo->name;
            $item['code69'] = $goodsInfo->code69;
            $item['cate_name'] = $cate_model->where('id', $item['dealer_cate_id'])->withTrashed()->value('name');
            $dealer_data = $dealer_model->where('id', $item['dealer_id'])->field('name,tc_rate,tp_rate,tx_rate')->withTrashed()->find();
            $item['dealer_name'] = $dealer_data['name'];


            $item['total_out_num'] = '';
            $total_out_num_small = 0;
            //原数据错误 其实 middle_unit_out_num是大单位

            if (!empty($item['middle_unit_out_num'])) {
                $name = DealerGoodsSpec::where([['dealer_goods_id', '=', $item['dealer_goods_id']], ['unit_type', '=', 2]])->value('unit');
                $item['total_out_num'] .= $item['middle_unit_out_num'] . $name;
                $spec_info = DealerGoodsSpec::where([['dealer_goods_id', '=', $item['dealer_goods_id']], ['unit_type', '=', 2]])->find();
                if (empty($spec_info->ratio)) {
                    $ratio = 1;
                } else {
                    $ratio = $spec_info->ratio;
                }
                $total_out_num_small += $ratio * $item['middle_unit_out_num'];
            }
            if (!empty($item['big_unit_out_num'])) {
                $spec_info = DealerGoodsSpec::where([['dealer_goods_id', '=', $item['dealer_goods_id']], ['unit_type', '=', 3]])->find();
                if($spec_info && $spec_info->uint){
                    $item['total_out_num'] .= $item['big_unit_out_num'] . $spec_info->unit ?? '';
                    $spec_info = DealerGoodsSpec::where([['dealer_goods_id', '=', $item['dealer_goods_id']], ['unit_type', '=', 3]])->find();
                    if (empty($spec_info->ratio)) {
                        $ratio = 1;
                    } else {
                        $ratio = $spec_info->ratio;
                    }
                    $total_out_num_small += $ratio * $item['big_unit_out_num'];
                }
            }
            if (!empty($item['small_unit_out_num'])) {
                $name = DealerGoodsSpec::where([['dealer_goods_id', '=', $item['dealer_goods_id']], ['unit_type', '=', 1]])->value('unit');
                $item['total_out_num'] .= $item['small_unit_out_num'] . $name;

                $total_out_num_small += $item['small_unit_out_num'];
            }
            $item['total_out_num_small'] = $total_out_num_small;
            // 获取经销商费率
            $item['total_out_value'] = sprintf("%.2f", $item['total_out_value']);
            // 服务费
            $tc_money = floatval($item['total_out_value']) * $dealer_data->tc_rate / 100;
            $tp_rate = floatval($item['total_out_value']) * $dealer_data->tp_rate / 100;
            $tx_rate = floatval($item['total_out_value']) * $dealer_data->tx_rate / 100;
            $item['service_fee'] = sprintf("%.2f", $tc_money + $tp_rate + $tx_rate);
            // 获取大中小单位
            $unit_name = '';
            if ($item['big_unit_id']) {
                $name = DealerGoodsSpec::where('id', $item['big_unit_id'])->value('unit');
                $unit_name = $name . '(' . $item['big_unit_out_num'] . ')';
            }
            if ($item['middle_unit_id']) {
                $name = DealerGoodsSpec::where('id', $item['middle_unit_id'])->withTrashed()->value('unit');
                $unit_name .= $name . '(' . $item['middle_unit_out_num'] . ')';
            }
            if ($item['small_unit_id']) {
                $name = DealerGoodsSpec::where('id', $item['small_unit_id'])->withTrashed()->value('unit');
                $unit_name .= $name . '(' . $item['small_unit_out_num'] . ')';
            }
            $item['unit_name'] = $unit_name;
        };
        return $list;
    }

    public function put_in_storage_cg($param)
    {
        $where = [];
        if (isset($param['type'])) {
            $where[] = ['order_type', '=', $param['type']];
        } else {
            $where[] = ['order_type', '=', 1];
        }
        $filter = [];

        if (isset($param['filter'])) {
            $filter = json_decode(stripslashes($param['filter']), true);
        }
        if (!empty($filter['create_time'])) {
            [$beginTime, $endTime] = $filter['create_time'];
            $where[] = ['time', '>=', $beginTime];
            $where[] = ['time', '<=', $endTime];
        }

        if (!empty($filter['goods_name'])) {
            $goodsIds = DealerGoods::where('name', 'like', '%' . $filter['goods_name'] . '%')->column('id');
            $where[] = ['dealer_goods_id', 'in', $goodsIds];
        }
        if (!empty($filter['dealer_name'])) {
            $dealerIds = DealerGoodsSpec::where('dealer_name', 'like', '%' . $filter['dealer_name'] . '%')->column('dealer_id');
            $where[] = ['dealer_id', 'in', $dealerIds];
        }
        if (!empty($filter['goods_cate_id'])) {
            $where[] = ['goods_cate_id', '=', $filter['goods_cate_id']];
        }
        if (!empty($filter['dealer_id'])) {
            $where[] = ['dealer_id', '=', $filter['dealer_id']];
        }
        $dealer_order_model = new DealerOrder();
        $id_arr = $dealer_order_model->where($this->defaultWhere)->where([['order_status', '=', 3]])->column('id');
        if (count($id_arr) > 0) {
            $ids = implode(",", $id_arr);
            $where[] = ['dealer_order_id', 'in', $ids];
        }
        $dealer_order_detail_model = new DealerOrderDetail();
        $sql = $dealer_order_detail_model->where($this->defaultWhere)->where($where)
            ->field('id,dealer_order_id,dealer_id,dealer_goods_id,order_type,num,dealer_goods_spec_id')
            ->with([
                'orders' => function ($query) {
                    $query->field('id,dealer_id,order_amount')->with([
                        'dealer' => function ($query) {
                            $query->field('id,name');
                        },
                    ]);
                },
                'goods' => function ($query) {
                    $query->field('id,name,image,cate_id,code69')->with([
                        'cate' => function ($query) {
                            $query->field('id,name');
                        }
                    ])->withTrashed();
                },
                'spec' => function ($query) {
                    $query->field('id,name,unit,sale_price,box_num,ratio');
                },
            ])->where($this->defaultWhere)
            ->order('id', 'desc')
            ->where($where);
        // var_dump($sql->fetchSql(true)->select());
        if (isset($param['export']) && $param['export'] == true) {
            $data = $sql->select()->toArray();

            $new_data = $this->fordata_cg($data);
        } else {
            $data = $sql->paginate($param['limit'] ?? 15)->toArray();
            $new_data = $this->fordata_cg($data['data']);
            $data['data'] = $new_data;

            //合计
            $all_data = $sql->select()->toArray();
            $all_data = $this->fordata_cg($all_data);
            $data['num_count'] = array_sum(array_column($all_data, 'num'));
            //小单位数量
            $data['small_unit_num_count'] = array_sum(array_column($all_data, 'small_unit_num'));
            //入库金额
            $data['value_count'] = sprintf("%.2f", array_sum(array_column($all_data, 'value')));
        }

        if (isset($param['export']) && $param['export'] == true) {
            $header = [
                ['商品名称', 'goods_name'],
                ['商品编码', 'code'],
                ['商品分类', 'goods_cate'],
                ['入库数量', 'num'],
                ['小单位数量', 'small_unit_num'],
                ['入库金额', 'value'],
                ['经销商', 'dealer_name'],
            ];


            $fileName = '入库报表';
            return Excel::exportData($new_data, $header, $fileName, 'xlsx');
        } else {

            return $this->success($data);
        }
    }

    public function fordata_cg($data)
    {
        foreach ($data as $k => $v) {
            // print_r($v);
            $new_data[$k]['id'] = $v['id'];
            $new_data[$k]['dealer_goods_spec_id'] = $v['dealer_goods_spec_id'];
            $new_data[$k]['goods_cate_id'] = $v['goods']['cate_id'];
            //商品名称
            $new_data[$k]['goods_name'] = isset($v['goods']['name']) ? $v['goods']['name'] : '';
            // 商品编码
            $new_data[$k]['code'] = $v['goods']['code69'] ?? '';
            // 商品分类
            $new_data[$k]['goods_cate'] = $v['goods']['cate']['name'];

            //入库数量
            $new_data[$k]['num'] = $v['num'];

            //小单位数量
            //规格box_num*订单num
            if (isset($v['spec']['ratio'])) {
                $ratio = $v['spec']['ratio'];
            } else {
                $ratio = 1;
            }
            $new_data[$k]['small_unit_num'] = $ratio * $v['num'];
            // 入库货值
            //规格表的售价*订单详情表的数量
            if (!empty($v['spec']) && !empty($v['spec']['sale_price'])) {
                $sale_price = $v['spec']['sale_price'];
            } else {
                $sale_price = 1;
            }
            $new_data[$k]['value'] = sprintf("%.2f",  $sale_price  * $v['num']);

            //  服务费用//zh暂时不统计
            //  经销商
            $new_data[$k]['dealer_name'] = $v['orders']['dealer']['name'];
        }
        return $new_data;
    }

    public function put_in_storage()
    {
        $param = $this->request->get();
        if (isset($param['type']) && $param['type'] == 1) {
            //采购入库
            return $this->put_in_storage_cg($param);
        } else {
            //销退入库
            return $this->put_in_storage_xt($param);
        }
    }

    /**
     * @NodeAnnotation(title="采购入库报表，销退入库报表 ")
     */
    public function put_in_storage_xt($param)
    {



        $where = [];
        //销退入库
        $where[] = ['goods_type', '=', 3];
        $filter = [];

        if (isset($param['filter'])) {
            $filter = json_decode(stripslashes($param['filter']), true);
        }
        if (!empty($filter['create_time'])) {
            [$beginTime, $endTime] = $filter['create_time'];
            $where[] = ['time', '>=', $beginTime];
            $where[] = ['time', '<=', $endTime];
        }

        if (!empty($filter['goods_name'])) {
            $goodsIds = DealerGoods::where('name', 'like', '%' . $filter['goods_name'] . '%')->column('id');
            $where[] = ['dealer_goods_id', 'in', $goodsIds];
        }
        if (!empty($filter['dealer_name'])) {
            $dealerIds = DealerGoodsSpec::where('dealer_name', 'like', '%' . $filter['dealer_name'] . '%')->column('dealer_id');
            $where[] = ['dealer_id', 'in', $dealerIds];
        }
        if (!empty($filter['goods_cate_id'])) {
            $where[] = ['goods_cate_id', '=', $filter['goods_cate_id']];
        }
        if (!empty($filter['dealer_id'])) {
            $where[] = ['dealer_id', '=', $filter['dealer_id']];
        }
        $company_order_model = new CompanyOrder();
        $id_arr = $company_order_model->where($this->defaultWhere)->where([['order_status', '=', 3]])->column('id');
        if (count($id_arr) > 0) {
            $ids = implode(",", $id_arr);
            $where[] = ['company_order_id', 'in', $ids];
        }

        $company_order_detail_model = new CompanyOrderDetail();
        $sql = $company_order_detail_model->where($this->defaultWhere)->where($where)
            ->field('id,company_order_id,dealer_id,dealer_goods_id,num,dealer_goods_spec_id')
            ->with([
                'order' => function ($query) {
                    $query->field('id,dealer_id,order_amount')->with([
                        'dealer' => function ($query) {
                            $query->field('id,name');
                        },
                    ]);
                },
                'goods' => function ($query) {
                    $query->field('id,name,image,cate_id,code69')->with([
                        'cate' => function ($query) {
                            $query->field('id,name');
                        }
                    ])->withTrashed();
                },
                'goodsSpec' => function ($query) {
                    $query->field('id,name,unit,sale_price,box_num,ratio');
                },
            ])
            ->order('id', 'desc')
            ->where($where);

        // var_dump($sql->fetchSql(true)->select());
        if (isset($param['export']) && $param['export'] == true) {
            $data = $sql->select()->toArray();
            $new_data = $this->for_put_in($data);
        } else {

            $data = $sql->paginate($param['limit'] ?? 15)->toArray();
            $new_data = $this->for_put_in($data['data']);
            $data['data'] = $new_data;


            //合计
            $all_data = $sql->select()->toArray();
            $all_data = $this->for_put_in($all_data);
            $data['num_count'] = array_sum(array_column($all_data, 'num'));
            $data['small_unit_num_count'] = array_sum(array_column($all_data, 'small_unit_num'));
            $data['value_count'] = array_sum(array_column($all_data, 'value'));
        }

        if (isset($param['export']) && $param['export'] == true) {
            $header = [
                ['商品名称', 'goods_name'],
                ['商品编码', 'code'],
                ['商品分类', 'goods_cate'],
                ['入库数量', 'num'],
                ['小单位数量', 'small_unit_num'],
                ['入库金额', 'value'],
                ['经销商', 'dealer_name'],
            ];


            $fileName = '入库报表';
            return Excel::exportData($new_data, $header, $fileName, 'xlsx');
        } else {
            return $this->success($data);
        }
    }

    public function for_put_in($data)
    {
        $new_data = [];
        foreach ($data as $k => $v) {
            // print_r($v);
            // $new_data[$k]['id'] = $v['id'];
            // $new_data[$k]['dealer_goods_id'] = $v['dealer_goods_id'];
            $new_data[$k]['goods_cate_id'] = $v['goods']['cate_id'];
            //商品名称
            $new_data[$k]['goods_name'] = isset($v['goods']['name']) ? $v['goods']['name'] : '';
            // 商品编码
            $new_data[$k]['code'] = $v['goods']['code69'] ?? '';
            // 商品分类
            $new_data[$k]['goods_cate'] = $v['goods']['cate']['name'];

            //入库数量
            $new_data[$k]['num'] = $v['num'];

            //小单位数量
            if (isset($v['goodsSpec']['ratio'])) {
                $ratio = $v['goodsSpec']['ratio'];
            } else {
                $ratio = 1;
            }
            //规格box_num*订单num
            $new_data[$k]['small_unit_num'] = $ratio * $v['num'];

            // 入库货值
            //规格表的售价*订单详情表的数量
            $new_data[$k]['value'] = sprintf("%.2f", $v['goodsSpec']['sale_price'] * $v['num']);


            //  服务费用//zh暂时不统计


            //  经销商
            $new_data[$k]['dealer_name'] = $v['order']['dealer']['name'];
        }
        return $new_data;
    }

    /**
     * @NodeAnnotation(title="更新经销商订单数据 ")
     */
    public function update_dealer()
    {
        $dealer_order_detail_model = new DealerOrderDetail();
        $dealer_order_model = new DealerOrder();
        $list = $dealer_order_detail_model->limit(500)->where('dealer_id', 'null')->field('id,dealer_order_id,dealer_goods_id')->select()->toArray();
        //->limit(1)
        if (count($list) > 0) {
            $goods_model = new DealerGoods();
            foreach ($list as $k => $v) {
                //获取经销商订单company_id
                $order_info = $dealer_order_model->field('id,company_id,order_type,dealer_id')->find($v['dealer_order_id'])->toArray();
                // var_dump($order_info);
                // print_r($v);
                $cate_id = $goods_model->where('id', $v['dealer_goods_id'])->value('cate_id');
                //更新经销商订单详情表company_id
                $dealer_order_detail_model->where(['dealer_order_id' => $v['dealer_order_id']])
                    ->update([
                        'company_id' => $order_info['company_id'],
                        'order_type' => $order_info['order_type'],
                        'dealer_id' => $order_info['dealer_id'],
                        'goods_cate_id' => $cate_id
                    ]);
            }
        } else {
            print_r('没有数据');
        }
    }

    public function update_company_order_detail()
    {

        try {
            $company_order_model = new CompanyOrder();
            $comapny_order_detail_model = new CompanyOrderDetail();
            $data = $comapny_order_detail_model->field('company_id,company_order_id,id')->limit(500)->where('dealer_id', 'null')->whereOr('company_id', 'null')->select();
            // ->limit(2)
            // print_r($data->toArray());
            if (count($data) > 0) {

                foreach ($data as $k => $v) {
                    // var_dump($v->company_order_id);
                    $order_data = $company_order_model->field('id,dealer_id,company_id')->where('id', $v->company_order_id)->withTrashed()->find();
                    // var_dump($order_data);
                    if (!empty($order_data->dealer_id)) {
                        $comapny_order_detail_model->where('company_order_id', $v->company_order_id)->update(['dealer_id' => $order_data->dealer_id, 'company_id' => $order_data->company_id]);
                    } else {
                        $comapny_order_detail_model->where('company_order_id', $v->company_order_id)->delete();
                    }
                }
            } else {
                print_r("无数据");
            }
        } catch (\Exception $e) {
            print_r($e->getMessage());
        };
    }

    /**
     * @NodeAnnotation(title="仓库 修改订单详情表字段 delivery_status")
     */
    public function update_company_order()
    {
        $comapny_order_detail_model = new CompanyOrderDetail();
        $company_order_model = new CompanyOrder();
        $list = $comapny_order_detail_model->limit(200)->where('delivery_status', 'null')
            ->field('id,company_order_id')->select()->toArray();
        //->limit(1)
        // print_r($list);
        if (count($list) > 0) {
            foreach ($list as $k => $v) {
                //获取经销商订单company_id
                $order_info = $company_order_model->field('id,delivery_status')->find($v['company_order_id']);
                if ($order_info) {

                    //更新经销商订单详情表company_id
                    $comapny_order_detail_model->where(['company_order_id' => $v['company_order_id']])
                        ->update([
                            'delivery_status' => $order_info['delivery_status']
                        ]);
                }
            }
        } else {
            print_r('没有数据');
        }
    }

    //更新 report_goods_out_job

    public function update_ck()
    {

        //从拣货单获取数据 
        $CompanyPickOrder_model = new CompanyPickOrder();
        $pick_data = $CompanyPickOrder_model->where([['pick_order_status', '=', 3]])->select()->toArray();

        foreach ($pick_data as $k => $v) {
            Queue::push(ReportGoodsOutJob::class, $v, 'report_goods_out');
        }
    }


    /**
     * @NodeAnnotation(title="仓库 采退出库报表//不用了 ")
     */
    public function storehouse()
    {
        $param = $this->request->post();
        //        $dealer_goods = new DealerGoods();
        $company_order = new CompanyOrder();
        $skip = ceil(($param['page'] - 1) * $param['limit']);
        $limit = $param['limit'];
        $where = [];
        /* if ($param['order_type'] == 1) {
            //采购单

        } else if ($param['order_type'] == 2) {
            //采退单

        }*/
        $sql = $company_order->field('id,out_status,dealer_id')->with([
            'detail' => function ($query) {
                $query->field('id,company_order_id,dealer_goods_id,num')->with([
                    'goods' => function ($query) {
                        $query->field('id,name,code69,cate_id')->with([
                            'cate' => function ($query) {
                                $query->field('id,name');
                            }
                        ]);
                    },

                ]);
            },
            "dealer" => function ($query) {
                $query->field('id,name');
            }

        ])->where('order_type', 1)
            ->where($where)
            ->where('out_status', 2)
            ->order($this->sort);
        $list = $sql->paginate($limit ?? 10)->toArray();
        $new_data = [];
        // var_dump($list['data']);
        foreach ($list['data'] as $k => &$vo) {
            //商品名称
            //    $new_data[]['goods_name'] = $vo['detail']['goods']['name'];

            //商品编码
            //    $new_data[]['goods_code'] = $vo['detail']['goods']['code69'];

            // 商品分类
            // $new_data[]['goods_cate'] = $vo['detail']['goods']['cate']['name'];

            //出库数量


            //出库货值


            //服务费用


            // 经销商

        }


        return $this->success($list);
    }
}
